# 1.使用pytorch，完成二分类处理
# (1)数据处理
# ①读取data-03-diabetes.csv数据
import matplotlib.pyplot as plt
import numpy as np
import torch

data = np.loadtxt('data-03-diabetes.csv', delimiter=',')
x_data = data[:, :-1]
y_data = data[:, -1:]
# ②将x，y转换成tensor处理
x = torch.Tensor(x_data)
y = torch.Tensor(y_data)
# (2)模型处理
# ①创建逻辑回归模型
model = torch.nn.Sequential(
    torch.nn.Linear(in_features=8, out_features=1),
    torch.nn.Sigmoid())
# ②配合随机梯度下降，调整合适的学习率
op = torch.optim.SGD(params=model.parameters(), lr=0.01)
# ③实现梯度下降过程
# ④代价函数使用pytorch底层实现
loss_fn = torch.nn.BCELoss()
loss_list = []
for i in range(20000):
    op.zero_grad()
    h = model(x)
    loss = loss_fn(h, y)
    loss.backward()
    op.step()
    loss_list.append(loss.data.numpy())
    if i % 200 == 0:
        print(i, loss.data.numpy())
# ⑤每200次打印代价值
# ⑥打印最终准确率
# ⑦绘制代价曲线
plt.plot(loss_list)
plt.show()
# ⑧打印所有预测结果
print((model(x) > 0.5).float())

#
# y_predict = (model(x) > 0.5).float()
# print(y_predict.numpy())
# acc = (y_predict == y).float().mean()
# print(acc)
